package com.tgr.shortLink.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tgr.shortLink.project.common.convention.result.Result;
import com.tgr.shortLink.project.common.convention.result.Results;
import com.tgr.shortLink.project.dto.req.LinkCreateReqDTO;
import com.tgr.shortLink.project.dto.req.LinkPageReqDTO;
import com.tgr.shortLink.project.dto.req.LinkUpdateReqDTO;
import com.tgr.shortLink.project.dto.resp.LinkCreateRespDTO;
import com.tgr.shortLink.project.dto.resp.LinkGroupQueryRespDTO;
import com.tgr.shortLink.project.dto.resp.LinkPageRespDTO;
import com.tgr.shortLink.project.service.LinkService;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 描述：短链接控制层
 * 作者：小陶不慌张
 * 文件：LinkController
 * 日期：2024/1/16 10:59
 */
@RequestMapping()
@RestController
@RequiredArgsConstructor
public class LinkController {

    private final LinkService linkService;

    /**
     * 创建短链接
     * @param requestParam
     * @return
     */
    @PostMapping("/api/short-link/link/v1/create")
    public Result<LinkCreateRespDTO> createLink (@RequestBody LinkCreateReqDTO requestParam){
        return Results.success(linkService.createLink(requestParam));
    }

    /**
     * 分页查询短链接
     * @param requestParam
     * @return
     */
    @GetMapping("/api/short-link/link/v1/page")
    public Result<IPage<LinkPageRespDTO>> pageLink( LinkPageReqDTO requestParam){
        return Results.success(linkService.pageLink(requestParam));
    }

    /**
     * 查询分组内短链接数量
     */
    @GetMapping("/api/short-link/link/v1/count")
    public Result<List<LinkGroupQueryRespDTO>> groupLinkCount(@RequestParam("gid") List<String> requestParam){
        return Results.success(linkService.groupLinkCount(requestParam));
    }

    /**
     * 短链接更新
     */
    @PostMapping("/api/short-link/link/v1/update")
    public Result<Void> updateLink(@RequestBody LinkUpdateReqDTO requestParam){
        linkService.updateLink(requestParam);
        return Results.success();
    }

    /**
     * 短链接跳转
     * @param shortUrl 短链接
     * @param request 请求信息
     * @param response 构建和发送响应
     */
    @GetMapping("{short-url}")
    public void restoreUrl(@PathVariable("short-url") String shortUrl, ServletRequest request, ServletResponse response){
        linkService.restoreUrl(shortUrl,request, response);
    }

    /**
     * 短链接获取标题
     */
    @GetMapping("/api/short-link/link/v1/title")
    public Result<String> getLinkTitle(@RequestParam("url") String url) {
        return Results.success(linkService.getLinkTitle(url));
    }

}
